package com.xiaomi.front.controller;

import com.xiaomi.front.service.shopp_cart.ShoppCartService;
import com.xiaomi.pojo.Shoppingcart;
import com.xiaomi.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class ShoppCartController {

    @Autowired
    private ShoppCartService shoppCartService;

    //添加购物车跳转页面/商品推荐 加购物车功能
    @RequestMapping(value = "/addCart")
    @ResponseBody
    public int addCart(@RequestParam("deid") int id, HttpSession session) {

        //获取session中的 user
        User loginuid = (User) session.getAttribute("user");

        //判断 购物车是否存在 存在则修改 不存在添加
        return shoppCartService.ExitsCart(loginuid.getUid(), id);
    }

    /*
    跳转购物车
    user = null 未登录 跳转 NullLogCar.jsp

     */
    @RequestMapping("/mycart")
    public String MyCart(HttpSession session, Model model) {

        //获取user
        User user = (User) session.getAttribute("user");

        if (user == null) {
            return "forward:/NullLogCar.jsp";
        } else {
            //获取购物车详情
            List<Shoppingcart> getShoppCart = shoppCartService.getShoppCart(user.getUid());

            if (getShoppCart.size() == 1 && getShoppCart.get(0) == null || 0 == getShoppCart.size()) {
                return "forward:/nullcart.jsp";
            } else {
                String name = user.getUname();
                model.addAttribute("name", name);
                model.addAttribute("getShoppCart", getShoppCart);
                return "front/shoppcart/mycart";
            }
        }

    }


    //根据deid商品编号/uid删除购物车详情
    @RequestMapping(value = "/delCart")
    @ResponseBody
    public int delCart(@RequestParam("deid") int[] id, HttpSession session) {

        //获取session中的 user
        User user = (User) session.getAttribute("user");

        //直接删
        return shoppCartService.DeleteShopp_cart(id, user.getUid());
    }

    //根据deid商品编号/uid 加购物车商品数量
    @RequestMapping(value = "/AddCartCount")
    @ResponseBody
    public int AddUserCart(@RequestParam("deid") int deid, HttpSession session) {

        //获取session中的 user
        User user = (User) session.getAttribute("user");

        //直接加
        return shoppCartService.UpdateShopp_cart(user.getUid(), deid);
    }

    //根据deid商品编号/uid  减购物车数量
    @RequestMapping(value = "/ReduceCart")
    @ResponseBody
    public int GoCart(@RequestParam("deid") int deid, HttpSession session) {

        //获取session中的 user
        User user = (User) session.getAttribute("user");

        //直接减
        return shoppCartService.reduceCart(user.getUid(), deid);
    }


}
